use std::ffi::c_void;
use std::alloc::{GlobalAlloc, Layout, System};
use once_cell::sync::Lazy;

// 使用 extern 块声明 C 函数
extern "C" {
    fn insert_alloction_info(ptr: usize, size: usize) -> c_void;
    fn remove_alloction_info(ptr: usize) -> c_void;
}

struct TrackingAllocator;

unsafe impl GlobalAlloc for TrackingAllocator {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let ptr = System.alloc(layout); // 使用系统分配器分配内存
        if !ptr.is_null() {
            let ptr_usize = ptr as usize;
            insert_alloction_info(ptr_usize, layout.size());
        }
        ptr
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        let ptr_usize = ptr as usize;
        remove_alloction_info(ptr_usize);
        System.dealloc(ptr, layout); // 使用系统分配器释放内存
    }
}

unsafe impl Sync for TrackingAllocator {}
unsafe impl Send for TrackingAllocator {}


#[global_allocator]
static GLOBAL: TrackingAllocator = TrackingAllocator;